﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.IdentityModel.Protocols.WSFederation;
using Microsoft.IdentityModel.Web;
using System.Web.Security;
using Microsoft.IdentityModel.Claims;
using System.Threading;

namespace LogOnWithACSLibrary
{
    /// <summary>
    /// A class contains helper functions.
    /// </summary>
    public class LogOnWithACS
    {
        /// <summary>
        /// A helper funtion to get wctx parameter.
        /// </summary>
        /// <param name="form">NameValueCollection</param>
        /// <returns>wctx parameter</returns>
        public static string GetUrlFromContext(FormCollection form)
        {
            WSFederationMessage message = WSFederationMessage.CreateFromNameValueCollection(new Uri("http://www.notused.com"), form);
            return (message != null ? message.Context : null);
        }

        /// <summary>
        /// A helper function to log off from federate sign on.
        /// </summary>
        public static void LogOff()
        {
            WSFederationAuthenticationModule fam = FederatedAuthentication.WSFederationAuthenticationModule;

            try
            {
                FormsAuthentication.SignOut();
            }
            finally
            {
                fam.SignOut(true);
            }
        }

        /// <summary>
        /// A helper function to get all the claims from the Identity.
        /// </summary>
        /// <returns>All the claims.</returns>
        public static ClaimCollection GetClaims()
        {
            IClaimsIdentity claimsIdentity = Thread.CurrentPrincipal.Identity as IClaimsIdentity;
            return claimsIdentity.Claims;
        }
    }
}
